<template>
  <q-page class="bg-grey-2">
    <div class="bg-white q-pa-md">
      <div class="q-gutter-md row">
        <div class="col col-md-auto row search-form-col items-center">
          <q-input
            v-model="data.minBudgetAmount"
            type="number"
            class="col"
            outlined
            label="最低预算"
            dense
          />
          <div class="col-auto q-px-md">~</div>
          <q-input
            v-model="data.maxBudgetAmount"
            type="number"
            class="col"
            outlined
            label="最高预算"
            dense
          />
        </div>
        <div
          class="col col-md-auto search-form-col"
          v-if="data.demands.tab === 3"
          style="min-width: 360px"
        >
          <div class="row q-gutter-x-sm">
            <q-select
              class="col"
              v-model="data.categoryTree.cate1.selected"
              :options="data.categoryTree.cate1.list"
              option-label="name"
              option-value="categoryId"
              label="一级"
              outlined
              dense
              clearable
            >
              <template v-slot:selected>
                <q-item-label lines="1" v-if="data.categoryTree.cate1.selected">
                  {{ data.categoryTree.cate1.selected.name }}
                </q-item-label>
              </template>
            </q-select>
            <q-select
              class="col"
              v-model="data.categoryTree.cate2.selected"
              :options="data.categoryTree.cate2.list"
              option-label="name"
              option-value="categoryId"
              label="二级"
              outlined
              dense
              clearable
              :disable="!data.categoryTree.cate1.selected"
            >
              <template v-slot:selected>
                <q-item-label lines="1" v-if="data.categoryTree.cate2.selected">
                  {{ data.categoryTree.cate2.selected.name }}
                </q-item-label>
              </template>
            </q-select>
            <q-select
              class="col"
              v-model="data.categoryTree.cate3.selected"
              :options="data.categoryTree.cate3.list"
              option-label="name"
              option-value="categoryId"
              label="三级"
              outlined
              dense
              clearable
              :disable="!data.categoryTree.cate2.selected"
            >
              <template v-slot:selected>
                <q-item-label lines="1" v-if="data.categoryTree.cate3.selected">
                  {{ data.categoryTree.cate3.selected.name }}
                </q-item-label>
              </template>
            </q-select>
          </div>
        </div>
        <div class="col col-md-auto row search-form-col" v-else>
          <q-select
            class="col"
            v-model="data.missState.value"
            :options="data.missState.options"
            label="需求状态"
            outlined
            dense
            emit-value
            :display-value="data.missState.label"
          >
          </q-select>
        </div>
        <div class="col col-md-auto row search-form-col">
          <q-btn color="primary" label="查询" unelevated @click="refresh(1)" />
        </div>
      </div>
    </div>

    <div class="q-gutter-y-md q-pa-md">
      <template v-if="data.list && data.list.length">
        <demands-item
          v-bind="item"
          v-for="(item, index) in data.list"
          :key="index"
          :account="data.accounts.current"
        ></demands-item>
      </template>
      <div class="text-center" v-else>暂无数据</div>
    </div>
    <div class="flex justify-center q-pa-md">
      <common-pagination
        v-model:page="data.pagination.page"
        :total="data.pagination.totalPage"
        v-if="data.pagination.totalPage > 1"
      ></common-pagination>
    </div>

    <div class="fixed-full" v-if="data.loading">
      <common-inner-loading></common-inner-loading>
    </div>
  </q-page>
</template>

<script>
import { fetchCategoryTree, fetchOutSourceList } from "src/assets/fetch";
import CommonInnerLoading from "src/components/CommonInnerLoading.vue";
import CommonPagination from "src/components/CommonPagination.vue";
import DemandsItem from "src/components/items/DemandsItem.vue";
import {
  computed,
  defineComponent,
  inject,
  reactive,
  watch,
  onUnmounted,
} from "vue";
import { useStore } from "vuex";

export default defineComponent({
  components: {
    DemandsItem,
    CommonPagination,
    CommonInnerLoading,
  },
  name: "IndexPage",
  setup() {
    const bus = inject("bus");
    const changeAccount = (val) => (data.accounts.tab = val);
    const changeDemand = (val) => (data.demands.tab = val);
    bus.on("changeAccountTab", changeAccount);
    bus.on("changeDemandTab", changeDemand);
    onUnmounted(() => {
      bus.off("changeAccountTab", changeAccount);
      bus.off("changeDemandTab", changeDemand);
    });

    const $store = useStore();
    const data = reactive({
      demandId: "",
      minBudgetAmount: "",
      maxBudgetAmount: "",
      missState: {
        options: [
          { label: "全部", value: 0 },
          { label: "可抢需求", value: 1 },
          { label: "错失需求", value: 2 },
        ],
        value: 1,
        label: computed(() => {
          const selected = data.missState.options.find(
            (v) => v.value === data.missState.value
          );
          return selected ? selected.label : "";
        }),
      },
      accounts: {
        list: computed(() => $store.getters["persisted/accounts"] || []),
        tab: 0,
        current: computed(() => data.accounts.list[data.accounts.tab]),
      },
      demands: {
        tab: 2,
        options: [
          { value: 1, label: "推荐" },
          { value: 2, label: "订阅" },
          { value: 3, label: "投标活动" },
        ],
      },
      pagination: {
        page: 1,
        totalPage: 0,
      },
      params: computed(() => {
        let param = {
          pageNum: data.pagination.page,
          pageSize: 20,
          reqType: data.demands.tab,
        };
        switch (data.demands.tab) {
          case 1:
            param["missState"] = data.missState.value;
            break;
          case 2:
            param["missState"] = data.missState.value;
            param["reqSource"] = 1;
            break;
          case 3:
            param["reqSource"] = 1;
            break;
        }
        if (data.minBudgetAmount != "") {
          param["minBudgetAmount"] = data.minBudgetAmount;
        }
        if (data.maxBudgetAmount != "") {
          param["maxBudgetAmount"] = data.maxBudgetAmount;
        }
        return param;
      }),
      categoryTree: {
        cate1: {
          selected: null,
          list: [],
        },
        cate2: {
          selected: null,
          list: computed(() => {
            if (!data.categoryTree.cate1.selected) {
              return [];
            }
            return data.categoryTree.cate1.selected.children;
          }),
        },
        cate3: {
          selected: null,
          list: computed(() => {
            if (!data.categoryTree.cate2.selected) {
              return [];
            }
            return data.categoryTree.cate2.selected.children;
          }),
        },
      },
      list: [],
      loading: false,
    });
    watch(
      () => [
        data.categoryTree.cate1.selected,
        data.categoryTree.cate2.selected,
      ],
      (val, old) => {
        if (val[0] !== old[0]) {
          data.categoryTree.cate2.selected = null;
        }
        data.categoryTree.cate3.selected = null;
      }
    );
    watch(
      () => data.accounts.current,
      (acc) => {
        if (!acc) {
          return;
        }

        fetchCategoryTree(acc.cookie).then((res) => {
          data.categoryTree.cate1.list = res.data;
        });
        refresh(1);
      },
      { immediate: true }
    );
    watch(
      () => data.demands.tab,
      () => refresh(1)
    );
    watch(() => data.pagination.page, refresh);

    function refresh(page) {
      if (page && data.pagination.page !== page) {
        data.pagination.page = page;
      } else {
        data.loading = true;
        fetchOutSourceList(data.params, data.accounts.current.cookie)
          .then((res) => {
            data.list = res.data;
            data.pagination.totalPage = res.totalPage;
          })
          .finally(() => (data.loading = false));
      }
    }

    return {
      data,
      refresh,
    };
  },
});
</script>

<style lang="scss" scoped>
.search-form-col {
  min-width: 220px;
}
</style>
